package com.example.lotterysystem.service.impl;

import com.example.lotterysystem.common.errorcode.ServiceErrorCodeConstants;
import com.example.lotterysystem.common.exception.ServiceException;
import com.example.lotterysystem.common.utils.CaptchaUtil;
import com.example.lotterysystem.common.utils.RedisUtil;
import com.example.lotterysystem.common.utils.RegexUtil;
import com.example.lotterysystem.service.VerificationCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.random.RandomGenerator;

/**
 * Created with IntelliJ IDEA.
 * Description: VerificationCodeService接口实现
 * User: Spider-Man
 * Date: 2025-09-09
 * Time: 17:04
 */
@Service
public class VerificationCodeServiceImpl implements VerificationCodeService {

    //对于Redis中key需要标准化:区分业务, 应该给key定义前缀: VerificationCode_1311111111:1234
    //User_13123131313:userInfo

    private static final String VERIFICATION_CODE_PREFIX = "VERIFICATION_CODE_";//业务区分前缀
    private static final Long  VERIFICATION_CODE_TIMEOUT = 60L;

    @Autowired
    private RedisUtil redisUtil;
    @Override
    public void sendVerificationCode(String phoneNumber) {
        //校验手机号
        if(!RegexUtil.checkMobile(phoneNumber)) {
            throw new ServiceException(ServiceErrorCodeConstants.PHONE_NUMBER_ERROR);
        }
        //生成随机验证码
        String code = CaptchaUtil.getCaptcha(4);
        /*
        发送验证码
        短信服务被限制个人使用,直接用缓存获取即可.
         */

        //缓存验证码
        redisUtil.set(VERIFICATION_CODE_PREFIX + phoneNumber,code,VERIFICATION_CODE_TIMEOUT);
    }

    @Override
    public String getVerificationCode(String phoneNumber) {
        //校验手机号
        if(!RegexUtil.checkMobile(phoneNumber)) {
            throw new ServiceException(ServiceErrorCodeConstants.PHONE_NUMBER_ERROR);
        }
        //返回生成的随机验证码
        return redisUtil.get(VERIFICATION_CODE_PREFIX + phoneNumber);
    }
}
